#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import logging

import pytest, requests
from utils import db
from pages.login import LoginPage
from pages.mainforce import MainForcePage
from pages.error import ErrorPage
from pages.earlytrade import EarlyTradePage
from pages.alert import Alert
from pages.calendar import Calendar
from pages.navibar import NaviBar
from pages.emotioncycle import EmotionCyclePage
from pages.stocksearch import StockSearchPage
from pages.stockdetail import StockDetailPage
from pages.stocktrack import StockTrackPage
from pages.plate import PlatePage
from pages.subscribe import SubscribePage
from pages.personal import PersonalPage
from pages.stocktrack4 import StockTrackPage4
from pages.earlytrade4 import EarlyTradePage4
from pages.stocktrack5 import StockTrackPage5

conn = None


@pytest.fixture(scope='session')
def mysql(env):
    global conn
    if conn is None:
        conn = db.Mysql(
            host=env['host'],
            dbuser=env['user'],
            password=env['password'],
            database=env['db']
        )
    return conn


@pytest.fixture
def loginPage(paged):
    return LoginPage(paged)


@pytest.fixture
def alert(paged):
    return Alert(paged)


@pytest.fixture
def naviBar(paged):
    return NaviBar(paged)


@pytest.fixture
def calendar(paged):
    return Calendar(paged)


@pytest.fixture
def mainForcePage(paged):
    return MainForcePage(paged)


@pytest.fixture
def earlyTradePage(paged):
    return EarlyTradePage(paged)


@pytest.fixture
def errorPage(paged):
    return ErrorPage(paged)


@pytest.fixture
def stockDetailPage(paged):
    return StockDetailPage(paged)


@pytest.fixture
def emotionCyclePage(paged):
    return EmotionCyclePage(paged)


@pytest.fixture
def stockSearchPage(paged):
    return StockSearchPage(paged)


@pytest.fixture
def stockTrackPage(paged):
    return StockTrackPage(paged)


@pytest.fixture
def platePage(paged):
    return PlatePage(paged)


@pytest.fixture
def subscribePage(paged):
    return SubscribePage(paged)


@pytest.fixture
def persionalPage(paged):
    return PersonalPage(paged)


@pytest.fixture
def earlyTradePage4(paged):
    return EarlyTradePage4(paged)


@pytest.fixture
def stockTrackPage4(paged):
    return StockTrackPage4(paged)


@pytest.fixture
def stockTrackPage5(paged):
    return StockTrackPage5(paged)


@pytest.fixture
def newUser(mysql):
    phone = '15828568760'
    yield phone
    sql = 'delete from site.sl_site_user where phone=%s'
    mysql.delete(sql, [phone])


@pytest.fixture
def get_code(mysql):
    def wrapper(phone):
        sql = 'select code from la_sms_log where mobile=%s order by id desc limit 1'
        return mysql.query(sql, [phone])[0]['code']

    return wrapper


@pytest.fixture
def get_auth_login_url(env):
    def wrapper(appid: str = env['app_id'], unionid: str = env['union_id'], courseNo: str = env['course_no']):
        url = env['base_url'] + '/api/data/site/create_auto_url'
        data = {
            "app_id": appid,
            "course_no": courseNo,
            "unionid": unionid
        }
        result = requests.post(url, json=data)
        return result.json()['result']['data']['url']

    return wrapper


@pytest.fixture
def pre_login(paged, loginPage, naviBar, env,state_file):
    """
    准备登录的fixture，确保页面加载并登录成功。

    参数:
    - paged: 页面操作对象，用于页面导航和等待。
    - loginPage: 登录页面对象，用于执行登录操作。
    - naviBar: 导航栏对象，用于检查导航栏状态。
    - env: 包含环境配置信息的字典，如电话号码和基础URL。
    - project_root: 项目根目录的路径对象。
    - cur_env_name: 当前环境的名称，用于构建状态文件路径。

    返回值:
    - wrapper: 一个函数，用于自动登录和保存登录状态。
    """
    def wrapper(courseNo=env['course_no']):
        """
        执行登录准备流程的函数。

        参数:
        - courseNo: 课程编号，默认使用环境变量中的课程编号。

        功能:
        - 转到指定课程页面。
        - 等待页面加载。
        - 如果导航栏隐藏，则执行预登录流程。
        - 保存登录状态到文件。
        """
        paged.goto(f'/{courseNo}')  # 转到指定课程页面
        paged.wait_for_timeout(3000)  # 等待页面加载
        if naviBar.naviBar.is_hidden():  # 如果导航栏隐藏，执行预登录
            if loginPage._pre_login(env['phone'], env['base_url']):
                paged.context.storage_state(path=state_file)  # 保存登录状态
                logging.info('保存登录状态！！！')
            else:
                logging.error('登录失败！！！')

    return wrapper

